package com.example.filter;

import com.alibaba.fastjson2.JSONObject;
import com.example.entity.Result;
import com.example.utils.MyJwtUtils;
import com.example.utils.MyThreadLocalUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/*@Component
@WebFilter(urlPatterns = "/*")// （/*）拦截所有请求*/
public class MyLoginFilter implements Filter {
    @Autowired
    private MyJwtUtils myJwtUtils;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("浏览器请求了==================================");
        //1.获取用户的请求路径，登录请求直接放行
        //转成子类型可以扩展很多功能
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();//获取资源路径
        //StringBuffer url = request.getRequestURL();//获取完整路径
        if(uri.contains("/login")){
            //登录请求直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;

        }

        //2.根据请求头Token获取令牌
        String token = request.getHeader("Token");
        //3.判断令牌是否合法，令牌合法则放行，令牌不合法则响应错误状态对象
        Map<String,Object> map = myJwtUtils.parseJwt(token);
        if(map==null){
            //说明令牌过期或不合法，直接响应错误信息
            //ThreadLocal 存储数据，线程安全
            Result<Object> result = Result.error("NOT_LOGIN_ERROR");
            //令牌不合法时，把result响应给前端（把对象转Json，并手动响应数据）
            String jsonString = JSONObject.toJSONString(result);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.getWriter().println(jsonString);
            return;


        }
        //合法的，把用户信息保存到ThreadLocal中，便于后续使用
        MyThreadLocalUtils.setValue(map);

        // 放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
